package com.youlian.utils.bitmap;


import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Handler;

import com.youlian.common.Configure;
import com.youlian.utils.Utils;
import com.youlian.utils.http.HTTPClientHelper;

public class AsyncLoadImage {

	private final Handler handler = new Handler();
    private final ExecutorService pool;
	public final Map<String, SoftReference<Bitmap>> cache;

	public boolean isDown=true;

	public AsyncLoadImage() {
		cache = Collections.synchronizedMap(new LinkedHashMap<String, SoftReference<Bitmap>>());
        pool = Executors.newFixedThreadPool(5);
	}


	public void stopDownLoad(){
		isDown = false;;
	}

	public void startDownLoad(){
		isDown = true;
	}
	public Bitmap loadDrawable(final String imageUrl, final Context context,final ImageCallback callback) {
		// 如果缓存过就从缓存中取出数据BaseApplication.getInstance().getBrandBitmapMap()
		if (cache.containsKey(imageUrl)) {
			SoftReference<Bitmap> softReference = cache.get(imageUrl);
			if (softReference.get() != null && !softReference.get().isRecycled()) {
				return softReference.get();
			}
		}
		if(isDown){
			// 缓存中没有图像，则从网络上取出数据，并将取出的数据缓存到内存中
			 pool.submit(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					 try {
							final Bitmap bitmap = loadImageFromUrl(imageUrl);
							handler.post(new Runnable() {
								public void run() {
									if (null != bitmap) {
										callback.imageLoaded(bitmap, imageUrl);
									}
								}
							});
						} catch (Exception e) {
							throw new RuntimeException(e);
						}
				}
			 });
		}

		return null;
	}

	/**
	 *
	 * @param imageUrl
	 *            图像url地址
	 * @param callback
	 *            回调接口
	 * @return 返回内存中缓存的图像，第一次加载返回null
	 */
	public Bitmap loadDrawables(final String imageUrl, final Context context,final ImageCallback callback) {
		// 如果缓存过就从缓存中取出数据BaseApplication.getInstance().getBrandBitmapMap()
		if (cache.containsKey(imageUrl)) {
			SoftReference<Bitmap> softReference = cache.get(imageUrl);
			if (softReference.get() != null && !softReference.get().isRecycled()) {
				return softReference.get();
			}
		}
		if(isDown){
			// 缓存中没有图像，则从网络上取出数据，并将取出的数据缓存到内存中
			 pool.submit(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					 try {
							final Bitmap bitmap = loadImageFromUrl(imageUrl);
							handler.post(new Runnable() {
								public void run() {
									if (null != bitmap) {
										callback.imageLoaded(bitmap, imageUrl);
									}
								}
							});
						} catch (Exception e) {
							throw new RuntimeException(e);
						}
				}
			 });
		}

		return null;
	}



	// 从网络上取数据方法
	protected Bitmap loadImageFromUrl(String imageUrl) {
		Bitmap bitmap = null;
		byte[] bytes;
		try {
			bytes = Utils.openStream(HTTPClientHelper.getInputStream(imageUrl));
			if (bytes!=null && bytes.length>500) {
				bitmap = BitmapUtils.getCorrectBmp(bytes, 0, Config.RGB_565);
				int bitmapWidth = bitmap.getWidth();
				float scale = (float) (Configure.pxWidth ) / bitmapWidth;
				Bitmap cornerBmp = BitmapUtils.getScaleBitmap(bitmap, scale);
				cache.put(imageUrl, new SoftReference<Bitmap>(cornerBmp));
				if(bitmap!= cornerBmp && bitmap!=null && !bitmap.isRecycled()){
					bitmap.recycle();
					bitmap = null;
				}
			    return cornerBmp;
			}
		} catch (IOException e) {e.printStackTrace();
		} catch (OutOfMemoryError e) {e.printStackTrace();
			System.gc();
		} catch (Exception e) { e.printStackTrace();
		}
		return null;
	}

	// 对外界开放的回调接口
	public interface ImageCallback {
		// 注意 此方法是用来设置目标对象的图像资源
		public void imageLoaded(Bitmap bitmap, String imageUrl);
	}
}
